package com.shut.vehicle.interceptor;

import com.shut.vehicle.interceptor.token.*;
import com.shut.vehicle.pojo.User;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Objects;

import static com.shut.vehicle.interceptor.token.UserThread.cleanLocalVar;


/**
 * @author 卢斌
 */
@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {


    private final RedisTemplate<String, String> redisTemplate;

    private final TokenCensor tokenCensor;

    public RequestInterceptor(RedisTemplate<String, String> redisTemplate, TokenCensor tokenCensor) {
        this.redisTemplate = redisTemplate;
        this.tokenCensor = tokenCensor;
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if(! (handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passToken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        } else if (method.isAnnotationPresent(Client.class)) {
            Client client = method.getAnnotation(Client.class);
            if (client.required()) {
                String token = request.getHeader("Authorization");
                User userEnt = null;
                if(StringUtils.isBlank(token)){
                    try {
                        this.userLoginTimeOut(Objects.requireNonNull(response));
                    } catch (IOException e) {
                        log.error("输出错误：", e);
                    }
                    return false;
                } else {
                    if ("test".equals(token)) {
                        userEnt = new User("124567890");
                        userEnt.setId(1);
                    }
                }
                // 通过用户Token，从Redis里查询该Token的密钥
                String sessionKey = redisTemplate.opsForValue().get(token);
                if (sessionKey != null) {
                    // 解密token获取用户个人信息
                    userEnt = tokenCensor.parseToken(token, sessionKey);
                }
                // 用户个人信息写入到线程容器中
                UserThread.setUserInfo(userEnt);
                return true;
            }
        } else if (method.isAnnotationPresent(Back.class)) {
            Back back = method.getAnnotation(Back.class);
            if (back.required()) {
                String token = request.getHeader("token");
                if (!StringUtils.isBlank(token)) {
                    return true;
                }
            }
        }
        this.userLoginTimeOut(response);
        return false;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        // 请求结束，从线程容器中清除用户信息
        cleanLocalVar();
    }


    /**
     * 拦截器拦截到用户请求后，如果不允许用户请求访问业务逻辑层则写回给用户登录超时信息
     * @param response HttpServletResponse
     * @throws IOException 写出到用户客户端失败
     */
    private void userLoginTimeOut(HttpServletResponse response) throws IOException {
        PrintWriter printWriter = response.getWriter();
        printWriter.write("loginAgain");
        printWriter.flush();
        printWriter.close();
    }

}